#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    GetNetInterface();
    m_goosePub = new Goose61850Publisher;
    connect(ui->cb_netInterface, &QComboBox::currentTextChanged, this, [this](const QString &arg1){
       if(m_goosePub!=NULL) m_goosePub->setInterface(arg1);
       qDebug() << arg1;
    });
    m_constantSendTimer = new QTimer;
    connect(m_constantSendTimer, &QTimer::timeout, this, [this](){
        m_goosePub->pubulisher();
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_publisher_clicked()
{
    m_goosePub->pubulisher();
}

void MainWindow::GetNetInterface()
{
    ui->cb_netInterface->clear();
    FILE* f = fopen("/proc/net/dev","r");
    char szLine[512];
    if (!f)
    {
        perror("socket");
        exit(1);
    }
    fgets(szLine, sizeof(szLine), f);
    fgets(szLine, sizeof(szLine), f);
    while(fgets(szLine, sizeof(szLine), f))
    {
        char szName[128] = {0};
        sscanf(szLine, "%s", szName);
        int nLen = strlen(szName);
        if (nLen <= 0)continue;
        if (szName[nLen - 1] == ',') szName[nLen - 1] = 0;
        if (strcmp(szName, "lo") == 0)continue;
        QString str = QString(szName);
        str = str.mid(0, str.size()-1);
        ui->cb_netInterface->addItem(str);
//        nCount++;
//        qDebug() << str.mid(0, str.size()-1);
    }
    ui->cb_netInterface->setCurrentText("lo");
}

void MainWindow::on_btn_conPub_clicked(bool checked)
{
    if(checked) m_constantSendTimer->start(500);
    else m_constantSendTimer->stop();
}
